package com.jh.user.business.impl;

import cn.jh.common.exception.ServiceException;
import cn.jh.common.pojo.BaseResponse;
import cn.jh.common.utils.BeanUtil;
import com.jh.user.business.StoreInfoBussiness;
import com.jh.user.pojo.CongMingChannel;
import com.jh.user.pojo.CongMingRate;
import com.jh.user.pojo.ShopRegister;
import com.jh.user.pojo.StoreInfo;
import com.jh.user.repository.CongMingChannelRepository;
import com.jh.user.repository.CongMingRateRepository;
import com.jh.user.repository.ShopRegisterRepository;
import com.jh.user.repository.StoreInfoRepository;
import com.jh.user.util.CommonsUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.*;

@Service
public class StoreInfoBussinessImpl implements StoreInfoBussiness {

    private Logger log = LoggerFactory.getLogger(StoreInfoBussinessImpl.class);

    @Autowired
    private EntityManager entityManager;

    @Autowired
    private ShopRegisterRepository shopRegisterRepository;

    @Autowired
    private StoreInfoRepository storeInfoRepository;

    @Autowired
    private CongMingRateRepository congMingRateRepository;

    @Autowired
    private CongMingChannelRepository congMingChannelRepository;

    @Override
    @Transactional
    public Object mergeStoreInfo(StoreInfo storeInfo) {
        storeInfo.setCreateTime(new Date());
        String uuid = System.currentTimeMillis() + "" + new Random().nextInt();
        storeInfo.setStoreNo(uuid);
        try {
            ShopRegister shopName = shopRegisterRepository.findByShopId(storeInfo.getShopId());
            if (shopName == null) {
                return CommonsUtil.returnError("商户号不存在");
            }
            StoreInfo byStoreNo = storeInfoRepository.findByStoreNo(uuid);
            if (byStoreNo != null && ! "".equals(byStoreNo.getStoreNo())) {
                return CommonsUtil.returnError("门店号已经存在，请稍后再试");
            }
            List<StoreInfo> result = storeInfoRepository.findStoreByPhoneAndShopId(storeInfo.getPhone(), storeInfo.getShopId());
            if (result.size() > 0) {
                return CommonsUtil.returnError("手机号已经存在，请稍后再试");
            }

            List<StoreInfo> results = storeInfoRepository.findStoreByEmailAndShopId(storeInfo.getEmail(), storeInfo.getShopId());
            if (results.size() > 0) {
                return CommonsUtil.returnError("邮箱已经存在，请稍后再试");
            }
            StoreInfo info = storeInfoRepository.save(storeInfo);
            entityManager.flush();
            return CommonsUtil.returnSuccess(info);
        }catch (Exception e){
            log.error("StoreInfoBussinessImpl.mergeStoreInfo, 添加异常=" + e);
            return CommonsUtil.returnError("添加失败！");
        }


    }

    private Specification<StoreInfo> where(final String shopId, final String shopName) {
        return new Specification<StoreInfo>() {
            @Override
            public Predicate toPredicate(Root<StoreInfo> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicates = new ArrayList<Predicate>();
                if (StringUtils.isNotBlank(shopId)) {
                    predicates.add(criteriaBuilder.equal(root.<String>get("shopId"), shopId));
                }
                if (StringUtils.isNotBlank(shopName)) {
                    predicates.add(criteriaBuilder.equal(root.<String>get("shopName"), shopName));
                }

                return criteriaQuery.where(predicates.toArray(new Predicate[predicates.size()])).getRestriction();
            }
        };
    }

    @Override
    public Page<StoreInfo> findByShopIdAndLegalNameAndShopName(String shopId, String shopName, Pageable pageable) {
        return storeInfoRepository.findAll(where(shopId, shopName), pageable);
    }


    @Override
    public Object findsShopNanmeByShopId(String shopId, Pageable pageables) {
        String shopName = "";
        try {
            ShopRegister shop = shopRegisterRepository.findByShopId(shopId);
            if (shop == null) {
                return CommonsUtil.returnError("商户号不存在");
            }
            List<StoreInfo> storeByShopId = storeInfoRepository.findStoreByShopId(shopId);
            if (storeByShopId.size() < 1) {
                return CommonsUtil.returnError("该商户没有门店");
            }
           return  BaseResponse.success("查询成功", storeInfoRepository.findAll(where(shopId, shopName), pageables));
        }catch (Exception e){
            log.error("StoreInfoBussinessImpl.findsShopNanmeByShopId, 查询异常=" + e);
            return CommonsUtil.returnError("查询失败！");
        }
    }

    @Override
    @Transactional
    public void updataStoreInfo(StoreInfo storeInfo) throws Exception {
        ShopRegister shopName = shopRegisterRepository.findByShopId(storeInfo.getShopId());
        if (shopName == null) {
            throw new Exception("商户号不存在");
        }

        //参数校验
        if (StringUtils.isBlank(storeInfo.getStoreNo())) {
            throw new Exception("門店不存在");
        }

        StoreInfo store = storeInfoRepository.findByStoreNo(storeInfo.getStoreNo());

        storeInfo.notUpdateProps();

        BeanUtil.copyPropertiesIgnoreNull(storeInfo, store);
        store.setCreateTime(new Date());
        entityManager.merge(store);
        entityManager.flush();
    }

    @Transactional
    @Override
    public StoreInfo updateStoreInfo(ShopRegister shopRegister) throws ServiceException {
        StoreInfo storeInfo = storeInfoRepository.findByShopId(shopRegister.getShopId());
        if (storeInfo == null) {
            return null;
        }
        if (StringUtils.isBlank(storeInfo.getStoreNo())) {
            throw new ServiceException("門店不存在");
        }

        storeInfo.update(shopRegister);

        storeInfoRepository.saveAndFlush(storeInfo);
        return storeInfo;
    }

    @Override
    @Transactional
    public void deleteStoreInfo(StoreInfo storeInfo) throws Exception {
        ShopRegister shopName = shopRegisterRepository.findByShopId(storeInfo.getShopId());
        if (shopName == null) {
            throw new Exception("商户号查询为空");
        }
        storeInfoRepository.deleteByShopIdAndStoreNo(storeInfo.getShopId(), storeInfo.getStoreNo());
        entityManager.clear();
        entityManager.flush();
    }

    @Override
    @Transactional
    public StoreInfo saveStoreInfo(StoreInfo storeInfo, long brandId) {
        // 新增快银支付通道个人费率
        List<CongMingRate> congMingRateList = new ArrayList<>();

        List<CongMingChannel> congMingChannelList = congMingChannelRepository.findAll();
        for (CongMingChannel congMingChannel : congMingChannelList) {
            CongMingRate congMingRate = new CongMingRate();
            congMingRate.addCongMingRate(congMingChannel, storeInfo.getUserId(), brandId);
            congMingRateList.add(congMingRate);
        }
        congMingRateRepository.save(congMingRateList);
        return storeInfoRepository.save(storeInfo);
    }

    @Override
    public StoreInfo findByShopId(String shopId) {
        return storeInfoRepository.findByShopId(shopId);
    }
}